package com.beta.cust.bind.provider;

import com.beta.cat.service.RedissonService;
import com.beta.cat.utils.JsonUtil;
import com.beta.cat.utils.sequence.seq.Sequence;
import com.beta.cust.bind.api.request.CrmQueryReq;
import com.beta.cust.bind.api.request.VerificationCodeReq;
import com.beta.cust.bind.api.service.IRpcCommonService;
import com.beta.cust.bind.api.service.IRpcCustService;
import com.beta.cust.bind.config.CfgSelfRefreshBean;
import com.beta.cust.bind.config.ResultCode;
import com.beta.cust.bind.constant.RedisConstant;
import com.beta.cust.bind.service.ICrmInterfaceService;
import com.beta.cust.bind.utils.CrmUtil;
import com.beta.elephant.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: pcc
 * @Date: 2024/3/28 15:28
 * @Description:
 */
@Slf4j
@DubboService
public class RpcCommonServiceImpl implements IRpcCommonService {

    @Autowired
    private ICrmInterfaceService crmInterfaceService;

    @Autowired
    private RedissonService redissonService;
    @Resource
    private Sequence smsSequence;
    @Resource
    private Sequence detailSequence;

    @Autowired
    private CfgSelfRefreshBean cfgSelfRefreshBean;

    @Autowired
    private IRpcCustService custService;

    @Override
    public ResultVO<Boolean> sendVerificationCode(VerificationCodeReq req) {
        if (StringUtils.isEmpty(req.getPhone())) {
            req.setPhone(custService.getLatestPhone(req.getUserId(), req.getCorpId()));
        }
        if (StringUtils.isEmpty(req.getPhone())) {
            return ResultVO.failure(ResultCode.ERROR_CODE_2105);
        }
        String sendResult = sendSmsCode(req.getPhone());
        return StringUtils.isEmpty(sendResult) ? ResultVO.success() :
                ResultVO.failure(ResultCode.ERROR_CODE_2107.getCode(), sendResult);
    }

    @Override
    public ResultVO<Map<String, String>> testCrmInterface(CrmQueryReq req) {
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("req", JsonUtil.toJson(req));
        try {
            if (!StringUtils.isEmpty(req.getCodePhone())) {
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("bsnNo", cfgSelfRefreshBean.getCrmSmsBsnNo());
                paramMap.put("reqBrcNo", cfgSelfRefreshBean.getCrmSmsReqBrcNo());
                paramMap.put("authNo", cfgSelfRefreshBean.getCrmSmsAuthNo());
                paramMap.put("cmsId", cfgSelfRefreshBean.getCrmSmsCmsId());
                paramMap.put("version", cfgSelfRefreshBean.getCrmSmsVersion());
                paramMap.put("csmSeqNo", "S" + smsSequence.nextValue());
                paramMap.put("mobile", req.getCodePhone());
                paramMap.put("svcId", cfgSelfRefreshBean.getCrmSmsSvcId());
                paramMap.put("text", req.getCode());
                String documentStr = CrmUtil.buildSmsDocStr(paramMap);
                resultMap.put("req", documentStr);
                resultMap.put("url", cfgSelfRefreshBean.getCrmSmsUrl());
                resultMap.put("svcId", cfgSelfRefreshBean.getCrmSmsSvcId());
                String interfaceResult = CrmUtil.sendXmlToESB(documentStr, cfgSelfRefreshBean.getCrmSmsSvcId(), cfgSelfRefreshBean.getCrmSmsUrl());
                resultMap.put("interfaceResult", interfaceResult);
                return ResultVO.success(resultMap);
            }
            if (!StringUtils.isEmpty(req.getCustPhone()) && !StringUtils.isEmpty(req.getCustManagePhone())) {
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("cmsId", cfgSelfRefreshBean.getCrmDetailCmsId());
                paramMap.put("version", cfgSelfRefreshBean.getCrmDetailVersion());
                paramMap.put("csmSeqNo", "D" + detailSequence.nextValue());
                paramMap.put("svcId", cfgSelfRefreshBean.getCrmDetailSvcId());
                paramMap.put("mgrPhone", req.getCustManagePhone());
                paramMap.put("cstPhone", req.getCustPhone());
                String documentStr = CrmUtil.buildDetailDocStr(paramMap);
                resultMap.put("req", documentStr);
                resultMap.put("url", cfgSelfRefreshBean.getCrmDetailUrl());
                resultMap.put("svcId", cfgSelfRefreshBean.getCrmDetailSvcId());
                String interfaceResult = CrmUtil.sendXmlToESB(documentStr, cfgSelfRefreshBean.getCrmDetailSvcId(), cfgSelfRefreshBean.getCrmDetailUrl());
                resultMap.put("interfaceResult", interfaceResult);
                return ResultVO.success(resultMap);
            }
            if (!StringUtils.isEmpty(req.getXmlParam())) {
                resultMap.put("req", req.getXmlParam());
                String interfaceResult = CrmUtil.sendXmlToESB(req.getXmlParam(), req.getSvcId(), req.getUrl());
                resultMap.put("interfaceResult", interfaceResult);
                return ResultVO.success(resultMap);
            }

        } catch (Exception e) {
            resultMap.put("error", ExceptionUtils.getStackTrace(e));
            log.error("testCrmInterface error:", e);
        }
        return ResultVO.success(resultMap);
    }

    /**
     * 生成验证码 并发送短信
     *
     * @param phone
     * @return
     */
    private String sendSmsCode(String phone) {
        // 生成4位随机数
        String randomNumber = RandomStringUtils.randomNumeric(4);
        log.info("sendSmsCode phone:{},code:{}", phone, randomNumber);
        String result = crmInterfaceService.sendSms(phone, randomNumber);
        if (StringUtils.isNotEmpty(result)) {
            return result;
        }
        String key = String.format(RedisConstant.PHONE_VERIFICATION_CODE, phone);
        redissonService.set(key, randomNumber);
        redissonService.expire(key, Duration.ofMinutes(10));
        return StringUtils.EMPTY;
    }
}
